package com.tianqingwl.gsystem.sysuser.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianqingwl.gsystem.sysuser.mapper.SysRoleMapper;
import com.tianqingwl.gsystem.sysuser.mapper.SysUserMapper;
import com.tianqingwl.gsystem.sysuser.pojo.SysRole;
import com.tianqingwl.gsystem.sysuser.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.util.*;

@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public void listSysRolePage(Page<SysRole> rolePage, Long userId, String roleName,Boolean idEq) {
        if (!StringUtils.isEmpty(roleName)){
            roleName="%"+roleName+"%";
        }
        sysRoleMapper.selectSysRolePage(rolePage,userId,roleName,idEq);

    }

    @Override
    public void removeUserRole(Long userId, Long roleId) {
        sysRoleMapper.deleteRole(userId,roleId);
    }

    @Override
    public SysRole save(SysRole sysRole) {
        if (sysRole == null) {
            return null;
        }

        Long roleId = sysRole.getRoleId();
        if (roleId == null) {

            sysRoleMapper.insert(sysRole);
            return sysRole;
        }
        sysRoleMapper.updateById(sysRole);
        return sysRole;
    }

    @Transactional
    @Override
    public void deleteById(Long roleId) {
        sysRoleMapper.deleteById(roleId);
        //删除角色权限关联
        sysRoleMapper.deleteRolePermission(roleId);
    }

    @Override
    public void deleteByIds(List<Long> roleIds) {
        sysRoleMapper.deleteBatchIds(roleIds);
    }

    @Override
    public void addPermission(Long roleId, Long[] permissionIds) {
        if (roleId!=null&&permissionIds!=null&&permissionIds.length>0){
            for (Long permissionId : permissionIds) {
                if (permissionId!=null){
                    sysRoleMapper.insertRolePermission(roleId,permissionId);
                }
            }
        }else{
            throw new RuntimeException("参数不足");
        }
    }

    @Override
    public SysRole getRoleById(Long roleId) {
        return sysRoleMapper.selectById(roleId);
    }

    @Override
    public boolean haveUser(List<Long> roleIds) {
        for (Long roleId : roleIds) {
            int count = sysUserMapper.countUserRole(roleId);
            if (count>0){
                return true;
            }
        }
        return false;
    }

}
